﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.ComponentModel;
using ITunesSolver.Helpers.DataVirtualization;
using ITunesSolver.Data;

namespace ITunesSolver.Helpers
{
	/// <summary>
	/// Demo implementation of IItemsProvider returning dummy customer items after
	/// a pause to simulate network/disk latency.
	/// </summary>
	public class PlaylistProvider : IItemsProvider<Playlist>
	{
        private HashSet<Playlist> _playlistsHashSet;

		/// <summary>
		/// Initializes a new instance of the <see cref="SongProvider"/> class.
		/// </summary>
		/// <param name="count">The count.</param>
		/// <param name="fetchDelay">The fetch delay.</param>
        public PlaylistProvider(HashSet<Playlist> playlistsHashSet)
		{
            _playlistsHashSet = playlistsHashSet;
		}

		/// <summary>
		/// Fetches the total number of items available.
		/// </summary>
		/// <returns></returns>
		public int Count
		{
			get
			{
                if (_playlistsHashSet == null) return 0;

                return _playlistsHashSet.Count;
			}
		}

		/// <summary>
		/// Fetches a range of items.
		/// </summary>
		/// <param name="startIndex">The start index.</param>
		/// <param name="count">The number of items to fetch.</param>
		/// <returns></returns>
		public IList<Playlist> FetchRange(int startIndex, int pageCount, out int overallCount)
		{
            //Trace.WriteLine("FetchRange: " + startIndex + "," + pageCount);
            //Thread.Sleep(_fetchDelay);

            overallCount = _playlistsHashSet.Count;

            //var list = from song in _songs
            //           where song.Index <= startIndex + pageCount && song.Index >= startIndex
            //           select song;

            return new List<Playlist>(_playlistsHashSet.AsParallel().Where((playlist, index) => index <= startIndex + pageCount && index >= startIndex).ToList());
		}

		/// <summary>
		/// Pretend to insert an item.
		/// </summary>
        //public void InsertItem()
        //{
        //    _count++;
        //    FirePropertyChanged("Count");
        //}

		/// <summary>
		/// Pretend to remove an item.
		/// </summary>
        //public void RemoveItem()
        //{
        //    _count--;
        //    FirePropertyChanged("Count");
        //}

		#region INotifyPropertyChanged Members

		public event PropertyChangedEventHandler PropertyChanged;
		protected void FirePropertyChanged(string property)
		{
			if (PropertyChanged != null)
				PropertyChanged(this, new PropertyChangedEventArgs(property));
		}
		#endregion

	}
}
